package com.awcall.iot.service.impl;

import com.awcall.iot.common.Tree;
import com.awcall.iot.model.Authority;
import com.awcall.iot.mapper.AuthorityMapper;
import com.awcall.iot.service.IAuthorityService;
import com.awcall.iot.utils.AuthorityTreeUtils;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 权限表 服务实现类
 * </p>
 *
 * @author wuhui
 * @since 2018-03-05
 */
@Service
public class AuthorityServiceImpl extends ServiceImpl<AuthorityMapper, Authority> implements IAuthorityService {

    @Override
    public Page<Authority> findPage(String title, Page<Authority> page) {
        List<Authority> authorityList = baseMapper.findByParams(title, page);
        page.setRecords(authorityList);
        return page;
    }

    @Override
    public List<Tree> findAuthorityTree(Integer roleId) {
        Wrapper<Authority> wrapper = new EntityWrapper<Authority>()
                .orderBy(String.format("`%s`", Authority.ORDER))
                .setSqlSelect(String.format("%s, %s, %s", Authority.ID, Authority.TITLE, Authority.PARENT_ID));
        List<Authority> allAuthorityList = selectList(wrapper);

        List<Authority> authorityList = baseMapper.findByRoleId(roleId);

        if (authorityList.size() > 0) {
            allAuthorityList.forEach(all -> authorityList.stream()
                    .filter(it -> Objects.equals(all.getId(), it.getId()))
                    .forEach(it -> all.setChecked(true)));
        }

        return AuthorityTreeUtils.build(allAuthorityList);
    }

    @Override
    public List<Tree> findAuthorityTree() {
        List<Authority> authorityList = baseMapper.findAuthorityTree();
        return AuthorityTreeUtils.build(authorityList);
    }

}
